﻿using HandyControl.Data;
using Newtonsoft.Json;
using Prism.Navigation.Regions;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using YY.Admin.Core;
using YY.Admin.Core.Const;
using YY.Admin.Core.EventBus;
using YY.Admin.Core.Session;
using YY.Admin.Services;
using YY.Admin.Services.Service.Auth;
using YY.Admin.Services.Service.Menu;
using YY.Admin.Views;
using YY.Admin.Views.SysManage;

namespace YY.Admin.ViewModels
{
    public class MenuItem
    {
        public string Name { get; set; } = string.Empty;
        public string Icon { get; set; } = string.Empty;
        // 图标可以是资源键或路径数据
        public string ViewName { get; set; } = string.Empty;
        public ObservableCollection<MenuItem> Children { get; set; } = [];
    }

    public class MainViewModel : BaseViewModel
    {
        private static readonly Dictionary<string, Type> _viewTypeCache = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
        private readonly ISysAuthService _authService;
        private readonly ISysMenuService _sysMenuService;
        private SysUser? _currentUser;
        private MenuItem? _selectedMenuItem;
        private string _menuLoadingMessage = "加载菜单中...";

        #region 标签集合
        public ObservableCollection<TabItemModel> OpenTabs { get; } = new ObservableCollection<TabItemModel>();
        private TabItemModel? _selectedTab;
        public TabItemModel? SelectedTab
        {
            get => _selectedTab;
            set
            {
                if (SetProperty(ref _selectedTab, value) && value != null)
                {

                    // 立即切换Tab，然后异步执行导航  --> 解决切换Tab卡顿的问题
                    _ = NavigateToSelectedTabAsync();
                }
            }
        }
        // 原来的 NavigateCommand 改为：
        public DelegateCommand<MenuItem> NavigateCommand { get; }

        // 添加 TabControl 关闭事件处理命令
        public DelegateCommand<RoutedEventArgs> TabClosedCommand { get; }

        #endregion
        public MainViewModel(
            ISysAuthService authService, 
            ISysMenuService sysMenuService,
            IContainerExtension _container,
            IRegionManager regionManager
            ) : base(_container, regionManager)
        {
            _authService = authService;
            Title = "后台管理系统";
            _sysMenuService = sysMenuService;
            // 订阅用户变更事件
            _currentUser = _authService.CurrentUser;
            _authService.UserChanged += OnUserChanged;
            LogoutCommand = new DelegateCommand(async () => await LogoutAsync());
            RetryLoadMenuCommand = new DelegateCommand(() => LoadMenuAsync());
            // ...
            NavigateCommand = new DelegateCommand<MenuItem>(OpenOrActivateTab);
            // 清空现有菜单
            MenuItems.Clear();
            // 异步初始化菜单
            LoadMenuAsync();
            // 默认导航到仪表盘（延迟执行）
            ScheduleDefaultNavigation();

            // 主题设置命令
            OpenThemeSettingsCommand = new DelegateCommand(OpenThemeSettings);
            ResetThemeSettingsCommand = new DelegateCommand(ResetThemeSettings);
            ApplyThemeSettingsCommand = new DelegateCommand(ApplyThemeSettings);
            SaveThemeSettingsCommand = new DelegateCommand(SaveThemeSettings);
            TabClosedCommand = new DelegateCommand<RoutedEventArgs>(OnTabClosed);
            // 加载初始主题设置
            LoadThemeSettings();
        }
        #region 主题
        private bool _isSettingsOpen;
        public bool IsSettingsOpen
        {
            get => _isSettingsOpen;
            set => SetProperty(ref _isSettingsOpen, value);
        }

        // 主题设置相关属性
        private SolidColorBrush _headerBrush = Brushes.White;
        public SolidColorBrush HeaderBrush
        {
            get => _headerBrush;
            set => SetProperty(ref _headerBrush, value);
        }

        private SolidColorBrush _menuBrush = (SolidColorBrush)new BrushConverter().ConvertFrom("#ffffff");
        public SolidColorBrush MenuBrush
        {
            get => _menuBrush;
            set => SetProperty(ref _menuBrush, value);
        }

        private SolidColorBrush _headerBackground = Brushes.White;
        public SolidColorBrush HeaderBackground
        {
            get => _headerBackground;
            set => SetProperty(ref _headerBackground, value);
        }

        private SolidColorBrush _menuBackground = (SolidColorBrush)new BrushConverter().ConvertFrom("#ffffff");
        public SolidColorBrush MenuBackground
        {
            get => _menuBackground;
            set => SetProperty(ref _menuBackground, value);
        }
        // 主题设置命令
        public ICommand OpenThemeSettingsCommand { get; }
        public ICommand ResetThemeSettingsCommand { get; }
        public ICommand ApplyThemeSettingsCommand { get; }
        public ICommand SaveThemeSettingsCommand { get; }

        #endregion
        public SysUser? CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }

        public ObservableCollection<MenuItem> MenuItems { get; } = [];

        public MenuItem? SelectedMenuItem
        {
            get => _selectedMenuItem;
            set => SetProperty(ref _selectedMenuItem, value);
        }
        public string MenuLoadingMessage
        {
            get => _menuLoadingMessage;
            private set => SetProperty(ref _menuLoadingMessage, value);
        }
 
        public DelegateCommand LogoutCommand { get; }
        public DelegateCommand RetryLoadMenuCommand { get; }
        private void OnUserChanged(object? sender, SysUser? user)
        {
            CurrentUser = user;
            //// 用户变更时刷新菜单
            //LoadMenuAsync();
        }
        /// <summary>
        /// 异步加载菜单【后续使用缓存以及权限管理】
        /// </summary>
        private async void LoadMenuAsync()
        {
            try
            {
                // 异步获取菜单数据
                var menuTree = await _sysMenuService.GetLoginMenuTree();
                // 转换菜单数据
                ConvertMenuTreeToViewModel(menuTree);
                // 添加默认菜单项（如果系统需要）
                AddDefaultMenuItems();
            }
            catch (Exception ex)
            {
                _logger.Error($"菜单加载失败: {ex.Message}", ex);
                MenuLoadingMessage = $"加载失败: {ex.Message}";
                // 显示错误菜单项
                MenuItems.Add(new MenuItem
                {
                    Name = "菜单加载失败",
                    Icon = "ErrorOutline",
                    ViewName = "ErrorView",
                    Children = { new MenuItem { Name = "点击重试", Icon = "Refresh" } }
                });
            }
            finally
            {
               
            }
        }
        /// <summary>
        /// 将服务层菜单树转换为视图模型
        /// </summary>
        private void ConvertMenuTreeToViewModel(List<MenuOutput> menuTree)
        {
            // 过滤并排序菜单项：只包含目录和菜单类型，排除按钮类型，并按排序号排序
            var rootMenus = menuTree
                .Where(m => m.Type == MenuTypeEnum.Dir || m.Type == MenuTypeEnum.Menu)
                .Where(m => m.Status == StatusEnum.Enable) // 只包含启用状态的菜单
                .Where(m => !(m?.IsHide ?? false)) // 排除隐藏的菜单
                .OrderBy(m => m.OrderNo)
                .ToList();
            // 递归转换菜单项
            void ConvertMenu(MenuOutput source, MenuItem target)
            {
                target.Name = source?.Title ?? source.Name;
                target.Icon = ConvertHtmlEntityToUnicode(source?.Icon ?? "&#xe810;");
                target.ViewName = source!.Path; // 根据组件路径获取视图名称

                // 添加子菜单（如果有）
                if (source.Children != null && source.Children.Any())
                {
                    // 过滤并排序子菜单
                    var childMenus = source.Children
                        .Where(c => c.Type == MenuTypeEnum.Menu) // 子菜单只包含菜单类型
                        .Where(c => c.Status == StatusEnum.Enable)
                        .Where(c => !(c?.IsHide ?? false))
                        .OrderBy(c => c.OrderNo)
                        .ToList();

                    foreach (var child in childMenus)
                    {
                        var childItem = new MenuItem();
                        ConvertMenu(child, childItem);
                        target.Children.Add(childItem);
                    }
                }
            }
            // 处理每个根菜单
            foreach (var root in rootMenus)
            {
                var rootItem = new MenuItem();
                ConvertMenu(root, rootItem);

                // 如果根菜单是目录但没有子菜单，则不显示
                if (root.Type == MenuTypeEnum.Dir && !rootItem.Children.Any())
                    continue;

                MenuItems.Add(rootItem);
            }
        }
        /// <summary>
        /// 添加默认菜单项
        /// </summary>
        private void AddDefaultMenuItems()
        {
            // 确保始终有仪表盘菜单
            //bool hasDashboard = false;
            //foreach (var item in MenuItems)
            //{
            //    if (item.ViewName == nameof(DashboardView))
            //    {
            //        hasDashboard = true;
            //        break;
            //    }
            //}

            //if (!hasDashboard)
            //{
            //    MenuItems.Insert(0, new MenuItem
            //    {
            //        Name = "仪表盘",
            //        Icon = "DashboardOutlined",
            //        ViewName = nameof(DashboardView)
            //    });
            //}
        }

        private async Task NavigateToSelectedTabAsync()
        {
            if (SelectedTab == null || string.IsNullOrEmpty(SelectedTab.ViewName))
                return;

            try
            {
                Debug.WriteLine($"开始后台异步导航到: {SelectedTab.ViewName}");

                //var regionManager = ContainerLocator.Current.Resolve<IRegionManager>();
                var tcs = new TaskCompletionSource<bool>();

                // 在UI线程执行导航（但不在属性设置的调用栈中）
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _regionManager.RequestNavigate(CommonConst.MAIN_WINDOW_REGION_NAME, SelectedTab.ViewName,
                        result =>
                        {
                            if (result.Success)
                            {
                                Debug.WriteLine($"导航成功: {SelectedTab.ViewName}");
                                tcs.SetResult(true);
                            }
                            else
                            {
                                Debug.WriteLine($"导航失败: {SelectedTab.ViewName}");
                                tcs.SetResult(false);
                            }
                        });
                }, DispatcherPriority.Background); // 使用较低优先级

                await tcs.Task;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"导航异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 打开或激活一个标签页（若已打开则激活，否则新建）
        /// </summary>
        private void OpenOrActivateTab(MenuItem menuItem)
        {
            //if (menuItem == null || string.IsNullOrEmpty(menuItem.ViewName))
            //    return;

            //var existing = OpenTabs.FirstOrDefault(t => string.Equals(t.ViewName, menuItem.ViewName, StringComparison.OrdinalIgnoreCase));
            //if (existing != null)
            //{
            //    // 延迟设置选中，防止 UI 尚未生成内容
            //    System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            //    {
            //        SelectedTab = existing;
            //    }), DispatcherPriority.Background);
            //    return;
            //}

            //var tab = new TabItemModel
            //{
            //    Header = menuItem.Name,
            //    Icon = menuItem.Icon,
            //    ViewName = menuItem.ViewName
            //};

            //tab.CloseCommand = new DelegateCommand(() => CloseTab(tab));

            //OpenTabs.Add(tab);

            //// 延迟设置选中项，等待模板生成并触发 TabContentView.Loaded
            //System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            //{
            //    SelectedTab = tab;
            //}), DispatcherPriority.Background);

            if (menuItem == null)
            {
                Debug.WriteLine("菜单项为空");
                return;
            }

            // 检查是否是父级菜单（有子菜单）
            if (menuItem.Children?.Count > 0)
            {
                Debug.WriteLine($"跳过父级菜单: {menuItem.Name}，它有 {menuItem.Children.Count} 个子菜单");
                return;
            }

            // 检查是否有有效的 ViewName
            if (string.IsNullOrEmpty(menuItem.ViewName))
            {
                Debug.WriteLine($"菜单没有 ViewName: {menuItem.Name}");
                return;
            }

            Debug.WriteLine($"点击菜单: {menuItem.Name}, ViewName: {menuItem.ViewName}");

            // 检查标签是否已打开
            var existingTab = OpenTabs.FirstOrDefault(t => t.ViewName == menuItem.ViewName);
            if (existingTab != null)
            {
                Debug.WriteLine($"切换到已存在标签: {menuItem.ViewName}");
                SelectedTab = existingTab;
                return;
            }

            // 创建新标签
            var newTab = new TabItemModel
            {
                Header = menuItem.Name,
                ViewName = menuItem.ViewName,
                Icon = menuItem.Icon,
            };

            Debug.WriteLine($"创建新标签: {menuItem.ViewName}");
            OpenTabs.Add(newTab);
            SelectedTab = newTab;
        }

        /// <summary>
        /// TabItem 关闭完成后触发
        /// </summary>
        private void OnTabClosed(RoutedEventArgs args)
        {
            if (args.OriginalSource is TabItemModel tabModel)
            {
                //var tabModel = tabItem.DataContext as TabItemModel;
                if (tabModel != null)
                {
                    Debug.WriteLine($"标签已关闭: {tabModel.Header}");

                    ClearViewFromRegion(tabModel.ViewName);

                    // 从集合中移除标签
                    //var idx = OpenTabs.IndexOf(tabModel);
                    //OpenTabs.Remove(tabModel);

                    //// 如果被选中的标签被关闭，尝试选中邻近的标签
                    //if (SelectedTab == tabModel)
                    //{
                    //    if (OpenTabs.Any())
                    //    {
                    //        var newIndex = Math.Min(idx, OpenTabs.Count - 1);
                    //        SelectedTab = OpenTabs[newIndex];
                    //    }
                    //    else
                    //    {
                    //        SelectedTab = null;
                    //        ClearContentRegion();
                    //    }
                    //}
                }
            }
        }

        /// <summary>
        /// 安排默认导航
        /// </summary>
        private void ScheduleDefaultNavigation()
        {
            System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                try
                {
                    // 改为打开仪表盘标签而不是请求 ContentRegion
                    // 假设你注册菜单或知道 Dashboard 的 ViewName 为 "DashboardView"
                    //var fakeMenu = new MenuItem { Name = "仪表盘", ViewName = nameof(DashboardView), Icon = "&#xe8b8;" };
                    var fakeMenu = new MenuItem { Name = "仪表盘", ViewName = nameof(DashboardView), Icon = ConvertHtmlEntityToUnicode("&#xe801;") };
                    OpenOrActivateTab(fakeMenu);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"默认导航失败: {ex.Message}");
                    _logger.Error($"默认导航失败: {ex.Message}", ex);
                }
            }), DispatcherPriority.ApplicationIdle);
        }

        /// <summary>
        ///导航跳转
        /// </summary>
        /// <param name="menuItem"></param>
        //private void Navigate(MenuItem? menuItem)
        //{
        //    if (menuItem == null || string.IsNullOrEmpty(menuItem.ViewName))
        //        return;

        //    try
        //    {
        //        Debug.WriteLine($"尝试导航到: {menuItem.ViewName}");

        //        // 检查视图是否存在
        //        var viewType = GetViewTypeByName(menuItem.ViewName);
        //        if (viewType == null)
        //        {
        //            Debug.WriteLine($"视图 '{menuItem.ViewName}' 不存在");
        //            NavigateToNotFound(menuItem.ViewName);
        //            return;
        //        }

        //        // 更新选中的菜单项
        //        SelectedMenuItem = menuItem;

        //        // 执行导航
        //        Debug.WriteLine($"导航到: {menuItem.ViewName}");
        //        RequestNavigate("ContentRegion", menuItem.ViewName);
        //    }
        //    catch (Exception ex)
        //    {
        //        Debug.WriteLine($"导航错误: {ex.Message}");
        //        NavigateToNotFound(menuItem.ViewName, ex.Message);
        //    }
        //}

        //private Type GetViewTypeByName(string viewName)
        //{
        //    // 检查缓存
        //    if (_viewTypeCache.TryGetValue(viewName, out var cachedType))
        //        return cachedType;

        //    // 获取应用程序中的所有程序集
        //    var assemblies = AppDomain.CurrentDomain.GetAssemblies();

        //    // 查找匹配的视图类型
        //    foreach (var assembly in assemblies)
        //    {
        //        try
        //        {
        //            // 尝试在程序集中查找匹配的类型
        //            var types = assembly.GetTypes();
        //            var viewType = types.FirstOrDefault(t =>
        //                t.Name.Equals(viewName, StringComparison.OrdinalIgnoreCase) &&
        //                typeof(FrameworkElement).IsAssignableFrom(t));

        //            if (viewType != null)
        //            {
        //                // 添加到缓存
        //                _viewTypeCache[viewName] = viewType;
        //                return viewType;
        //            }
        //        }
        //        catch (ReflectionTypeLoadException)
        //        {
        //            // 忽略无法加载类型的程序集
        //        }
        //        catch (Exception ex)
        //        {
        //            Debug.WriteLine($"扫描程序集 {assembly.FullName} 时出错: {ex.Message}");
        //        }
        //    }

        //    // 缓存未找到的结果
        //    _viewTypeCache[viewName] = null;
        //    return null;
        //}
        //private void NavigateToNotFound(string requestedView, string error = null)
        //{
        //    // 创建导航参数
        //    var parameters = new NavigationParameters();
        //    if (!string.IsNullOrEmpty(requestedView))
        //        parameters.Add("RequestedView", requestedView);

        //    if (!string.IsNullOrEmpty(error))
        //        parameters.Add("ErrorMessage", error);

        //    // 导航到404页面
        //    SafeNavigate("ContentRegion", "NotFoundView", parameters);

        //    // 重置菜单选择
        //    SelectedMenuItem = null;
        //}

        private async Task LogoutAsync()
        {
            await _authService.LogoutAsync();

            // 返回登录窗口
            System.Windows.Application.Current.MainWindow?.Hide();
            var loginWindow = new LoginWindow();
            System.Windows.Application.Current.MainWindow = loginWindow;
            loginWindow.Show();

            // 清空ContentRegion区域
            ClearRegion(CommonConst.MAIN_WINDOW_REGION_NAME);
        }

        /// <summary>
        /// 从区域中清空视图
        /// </summary>
        /// <param name="viewName"></param>
        private void ClearViewFromRegion(string viewName)
        {
            try
            {
                if (_RegionManager.Regions.ContainsRegionWithName(CommonConst.MAIN_WINDOW_REGION_NAME))
                {
                    var region = _RegionManager.Regions[CommonConst.MAIN_WINDOW_REGION_NAME];

                    // 查找并移除指定的视图
                    var viewToRemove = region.Views.FirstOrDefault(v =>
                    {
                        // 根据视图名称或类型来匹配
                        var viewType = v.GetType();
                        return viewType.Name == viewName || viewType.Name == viewName + "View";
                    });

                    if (viewToRemove != null)
                    {
                        region.Remove(viewToRemove);
                        Debug.WriteLine($"从区域移除视图: {viewName}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"清理视图失败: {ex.Message}");
            }
        }

        private string ConvertHtmlEntityToUnicode(string htmlEntity)
        {
            if (string.IsNullOrEmpty(htmlEntity))
                return "\ue7c6"; // 默认图标

            if (htmlEntity.StartsWith("&#x") && htmlEntity.EndsWith(";"))
            {
                string hexCode = htmlEntity.Substring(3, htmlEntity.Length - 4);
                if (int.TryParse(hexCode, NumberStyles.HexNumber, null, out int unicodeValue))
                {
                    return char.ConvertFromUtf32(unicodeValue);
                }
            }
            return htmlEntity;
        }
        #region 主题
        private void OpenThemeSettings()
        {
            // 加载当前应用到预览区
            HeaderBrush = HeaderBackground;
            MenuBrush = MenuBackground;
            IsSettingsOpen = true;
        }

        private void ResetThemeSettings()
        {
            // 重置为默认值
            HeaderBrush = Brushes.White;
            MenuBrush = (SolidColorBrush)new BrushConverter().ConvertFrom("#ffffff");
        }

        private void ApplyThemeSettings()
        {
            // 应用预览效果
            HeaderBackground = HeaderBrush;
            MenuBackground = MenuBrush;
        }

        private void SaveThemeSettings()
        {
            try
            {
                var settings = new ThemeSettings
                {
                    HeaderBackground = HeaderBrush.Color.ToString(),
                    MenuBackground = MenuBrush.Color.ToString()
                };

                // 保存到文件
                var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
                var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "themeSettings.json");
                File.WriteAllText(filePath, json);

                // 关闭设置面板
                IsSettingsOpen = false;

                // 应用最终设置
                ApplyThemeSettings();
                //通知主题变更
                _eventAggregator.GetEvent<ThemeChangedEvent>().Publish(settings);
            }
            catch (Exception ex)
            {
                _logger.Error($"保存主题设置失败: {ex.Message}", ex);
            }
        }

        private void LoadThemeSettings()
        {
            try
            {
                var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "themeSettings.json");
                if (File.Exists(filePath))
                {
                    var json = File.ReadAllText(filePath);
                    var settings = JsonConvert.DeserializeObject<ThemeSettings>(json);

                    if (!string.IsNullOrEmpty(settings.HeaderBackground))
                    {
                        HeaderBackground = new SolidColorBrush(
                            (Color)ColorConverter.ConvertFromString(settings.HeaderBackground));
                    }

                    if (!string.IsNullOrEmpty(settings.MenuBackground))
                    {
                        MenuBackground = new SolidColorBrush(
                            (Color)ColorConverter.ConvertFromString(settings.MenuBackground));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"加载主题设置失败: {ex.Message}", ex);
            }
        }
        #endregion

    }
}
